const { contextBridge, ipcRenderer } = require('electron');

// 错误处理包装函数
const safeInvoke = async (channel, ...args) => {
  try {
    return {
      result: await ipcRenderer.invoke(channel, ...args),
      error: null
    };
  } catch (error) {
    console.error(`IPC调用错误 [${channel}]:`, error);
    return {
      result: null,
      error: error.message || String(error)
    };
  }
};

contextBridge.exposeInMainWorld('electronAPI', {
  openFileDialog: () => safeInvoke('dialog:openFile'),
  showSaveDialog: () => safeInvoke('dialog:showSaveDialog'),
  readFile: (filePath) => safeInvoke('fs:readFile', filePath),
  writeFile: (filePath, content) => safeInvoke('fs:writeFile', filePath, content),
  
  // autoLaunch API
  getStatus: () => safeInvoke('auto-launch:get-status'),
  toggle: (enabled) => safeInvoke('auto-launch:toggle', enabled),
  
  // 语音合成权限请求
  requestSpeechPermission: () => safeInvoke('speech:request-permission'),
  
  // 监听心跳检测
  onHeartbeat: (callback) => {
    const listener = (event, timestamp) => callback(timestamp);
    ipcRenderer.on('heartbeat', listener);
    return () => ipcRenderer.removeListener('heartbeat', listener);
  }
});

// 防止上下文隔离被意外破坏
try {
  // 验证上下文隔离是否正常工作
  if (process.versions.electron && window.require) {
    console.warn('上下文隔离可能被破坏，这是不安全的！');
  }
} catch (e) {
  console.error('验证上下文隔离时出错:', e);
}
    